<?php

/**
 *
 * @author Anthony Straetman
 *
 */

class RegisterDB
{
	public static function Register($firstname, $lastname, $username, $email, $password, $passwordConfirm) {
		$firstnameRequiredMessage = "Firstname required";
		$lastnameRequiredMessage = "Lastname required";
		$usernameRequiredMessage = "Username required";
		$usernameTakenMessage = "Username has already been taken";
		$emailRequiredMessage = "Email required";
		$emailInvalidMessage = "Invalid email";
		$emailTakenMessage = "Email has already been taken";
		$passwordRequiredMessage = "Password required";
		$passwordInvalidMessage = "Password must be at least 5 characters long";
		$passwordsNotEqualMessage = "Passwords do not match";
		$passwordInvalidMessage = "Invalid password";
		
		$db = PlonkWebsite::getDB();
		$errors = array ();
		
		if(strlen(trim($firstname)) == 0)
			array_push($errors, $firstnameRequiredMessage);
		if(strlen(trim($lastname)) == 0) 
			array_push($errors, $lastnameRequiredMessage);
		if(strlen(trim($username)) == 0) 
			array_push($errors, $usernameRequiredMessage);
		if(strlen(trim($email)) == 0)
			array_push($errors, $emailRequiredMessage);
		else {
			if(!PlonkFilter::isEmail(trim($email)))
				array_push ($errors, $emailInvalidMessage);
		}
		if(strlen(trim($password)) == 0)
			array_push($errors, $passwordRequiredMessage);
		else {
			if(trim($password) != trim($passwordConfirm))
				array_push($errors, $passwordsNotEqualMessage);
			if(strlen(trim($password)) < 5)
				array_push($errors, $passwordInvalidMessage);
		}
		if(!RegisterDB::usernameAvailable($username))
			array_push($errors, $usernameTakenMessage);
		if(!RegisterDB::emailAvailable($email))
			array_push ($errors, $emailTakenMessage);
		
		if(sizeof($errors) == 0)
			RegisterDB::addUserToTmp($username, $firstname, $lastname, $email, $password);
		
		return $errors;
	}
	
	public static function usernameAvailable($username) {
		$db = PlonkWebsite::getDB();
		$user = $db->retrieveOne(sprintf('SELECT id FROM users WHERE username="%s"', $username));
		if(sizeof($user) == 0)
			return true;
		else
			return false;
	}
	
	public static function emailAvailable($email) {
		$db = PlonkWebsite::getDB();
		$user = $db->retrieveOne(sprintf('SELECT id FROM users WHERE email="%s"', $email));
		if(sizeof($user) == 0)
			return true;
		else
			return false;
	}
	
	public static function addUserToTmp($username, $firstname, $lastname, $email, $password) {
		$db = PlonkWebsite::getDB();
		$uniquecode = StringHelper::generateRandomString(25);
		$values = array(
			'firstname' => htmlentities($firstname),
			'lastname' => htmlentities($lastname),
			'username' =>  htmlentities($username),
			'email' =>  htmlentities($email),
			'password' => htmlentities($password),
			'uniquecode' => $uniquecode
		);
		$db->insert('tmpusers', $values);
	}
}

// EOF